package com.tianyang.yukuaifuzs.business.login.presenter;

import android.util.Log;

import com.tianyang.yukuaifuzs.business.login.bean.LoginOutput;
import com.tianyang.yukuaifuzs.business.login.contract.RegisterContract;
import com.tianyang.yukuaifuzs.business.login.model.LoginModel;
import com.tianyang.yukuaifuzs.business.login.view.LoginActivity;
import com.tianyang.yukuaifuzs.business.login.view.RegisterActivity;
import com.tianyang.yukuaifuzs.business.main.view.MainActivity;
import com.tianyang.yukuaifuzs.common.cache.CacheManage;
import com.tianyang.yukuaifuzs.common.cache.CacheModel;
import com.tianyang.yukuaifuzs.common.interfaces.CommonConfig;
import com.tianyang.yukuaifuzs.utils.AppContextUtil;
import com.tianyang.yukuaifuzs.utils.IntentTool;
import com.tianyang.yukuaifuzs.utils.ToastUtil;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：注册
 */

public class RegisterPresenter implements RegisterContract.Presenter {

    private RegisterContract.View mView;

    private CompositeSubscription mSubscription;

    public RegisterPresenter(RegisterContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void register(String accountName, String smsCode, String password, String shareCode) {
        mView.showLoadingDialog(true, "正在注册...");
        Subscription subscription = LoginModel.getInstance()
                .register(accountName, smsCode, password, shareCode)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginOutput>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(LoginOutput loginOutput) {
                        mView.dismissLoadingDialog();
                        if (loginOutput != null) {
                            ToastUtil.showTextViewPromptShort("注册成功！");
                            CacheManage.getInstance().saveCache(CacheModel.LOGIN_KEY, loginOutput);
                            CacheManage.getInstance().saveCache(CacheModel.IDENTITY, loginOutput.getIdentity());
                            IntentTool.startActivity(mView.getContext(), MainActivity.class);
                            AppContextUtil.finishActivity(LoginActivity.class.getName(), RegisterActivity.class.getName());
                        } else {
                            ToastUtil.showTextViewPrompt("请重新登录!");
                            IntentTool.finishActivity(mView.getContext());
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void sendCode(String phone) {
        if (!mView.checkParameter(true)) return;
        mView.showLoadingDialog(false);
        Subscription subscription = LoginModel.getInstance()
                .sendSms(phone, CommonConfig.SMSTYPE_REGISTER)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(Object s) {
                        ToastUtil.showTextViewPromptShort("验证码发送成功！");
                        showCountDown();
                    }
                });
        mSubscription.add(subscription);
    }

    private void showCountDown() {
        Observable.interval(0, 1, TimeUnit.SECONDS)//设置0延迟，每隔一秒发送一条数据
                .take(CommonConfig.SMS_SEC + 1) //设置循环次
                .map(new Func1<Long, Long>() {
                    @Override
                    public Long call(Long aLong) {
                        return CommonConfig.SMS_SEC - aLong;
                    }
                })
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        mView.changeByStatus(true);

                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onCompleted() {
                        mView.changeByStatus(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(Long aLong) { //接受到一条就是会操作一次UI
                        Log.e("Register", "onNext: " + aLong);
                        mView.byoyomi(aLong);
                    }
                });
    }

    @Override
    public void onDestroyPresenter() {
        if (mView != null)
            mView = null;
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
    }
}
